use Purple;
use Net::Twitter;

%PLUGIN_INFO = (
    perl_api_version => 2,
    name => "Status to Twitter",
    version => "0.1",
    summary => "Update twitter with your pidgin status",
    description => "Your twitter status will be updated to reflect the status set in a configured IM account using Pidgin",
    author => "Ethan Goldblum <egoldblum\@cmu.edu>",
    url => "http://code.google.com/p/pidgin-status-to-twitter",
    load => "plugin_load",
    unload => "plugin_unload",
    prefs_info => "prefs_info_cb"
);

sub plugin_init {
    return %PLUGIN_INFO;
}

sub plugin_load {
    my $plugin = shift;
    Purple::Prefs::add_none("/plugins/core/status_to_twitter");
    Purple::Prefs::add_string("/plugins/core/status_to_twitter/username", "");
    Purple::Prefs::add_string("/plugins/core/status_to_twitter/password", "");

    $status_handle = Purple::SavedStatuses::get_handle();
    Purple::Signal::connect($status_handle, "savedstatus-changed", $plugin, \&status_changed_cb, undef);
}

sub plugin_unload {
    my $plugin = shift;
}

sub prefs_info_cb {
    $frame = Purple::PluginPref::Frame->new();

    $ppref = Purple::PluginPref->new_with_name_and_label("/plugins/core/status_to_twitter/username", "Twitter Username");
    $ppref->set_type(2);
    $ppref->set_max_length(15);
    $frame->add($ppref);

    $ppref = Purple::PluginPref->new_with_name_and_label("/plugins/core/status_to_twitter/password", "Twitter Password");
    $ppref->set_type(2);
    $frame->add($ppref);
 
    return $frame;
}

sub status_changed_cb {
    my $username = Purple::Prefs::get_string("/plugins/core/status_to_twitter/username");
    my $password = Purple::Prefs::get_string("/plugins/core/status_to_twitter/password");
    my $twit = Net::Twitter->new({username=>$username, password=>$password});
    my ($new, $old) = @_;
    my $old_message = Purple::SavedStatus::get_message($old);
    my $new_message = Purple::SavedStatus::get_message($new);
    Purple::Debug::info("status_to_twitter", "Status changed from " . $old_message . " to " . $new_message . "\n");
    if ($old_message ne $new_message) {
        $twit->update({status => $new_message});
    }
}




